import json
from datetime import datetime
from django.db.models import CharField
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from dataset.models import DatasetInfo
from django.db.models.functions import Cast
from django.conf import settings
from collections import Counter
import numpy as np
import pandas as pd
import urllib
import requests
import execjs
import os


# Create chart views here.


class AQILineChart(View):
    """
    AQI线图视图类，用于处理AQI数据的GET和POST请求，展示AQI变化趋势线图。

    方法:
    - get: 处理GET请求，获取用户名，并渲染到AQI线图页面。
    - post: 处理POST请求，根据选定的省份获取对应的AQI数据，并以JSON格式返回。
    """

    def get(self, request):
        """
        处理GET请求，获取并返回用户姓名以及渲染线图的上下文。

        参数:
        - request: HttpRequest对象，包含客户端发来的HTTP请求信息。

        返回:
        - HttpResponse对象，渲染的AQI线图页面。
        """
        # 从请求的cookie中获取用户名
        username = request.COOKIES.get('user_name')
        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }
        # 渲染并返回AQI线图页面
        return render(request, 'chart/AQI-line-chart.html', context=context)

    def post(self, request):
        """
        处理POST请求，根据请求中指定的省份，查询并返回该省份的AQI数据。

        参数:
        - request: HttpRequest对象，包含客户端发来的HTTP请求信息。

        返回:
        - HttpResponse对象，包含指定省份的AQI数据的JSON响应。
        """
        # 从POST请求中获取省份信息
        province = request.POST.get('province')
        # 查询指定省份的AQI数据，并按时间降序排列
        province_aqi = DatasetInfo.objects.filter(province=province).order_by('-time')

        # 提取数据的日期和AQI值，转化为列表
        dates = [record[0] for record in province_aqi.values_list("time")]
        aqi_values = [record[0] for record in province_aqi.values_list("aqi")]

        # 将日期和AQI值列表封装为字典
        province_aqi_dict = {
            "dates": dates,
            "aqi_values": aqi_values
        }
        # 返回包含AQI数据的JSON响应
        return JsonResponse(province_aqi_dict)


class TrendChartOfPm2_5(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }

        return render(request, 'chart/trend-chart-of-pm2_5.html', context=context)

    def post(self, request):
        # 从POST请求中获取省份信息
        province = request.POST.get('province')
        # 查询指定省份的pm2.5数据，并按时间降序排列
        province_aqi = DatasetInfo.objects.filter(province=province).order_by('-time')
        # 提取数据的日期和pm2.5值，转化为列表
        dates = [record[0] for record in province_aqi.values_list("time")]
        pm2_5_values = [record[0] for record in province_aqi.values_list("pm2_5")]

        # 将日期和pm2.5值列表封装为字典
        province_dict = {
            "dates": dates,
            "pm2_5_values": pm2_5_values
        }
        # 返回包含AQI数据的JSON响应
        return JsonResponse(province_dict)


class TrendChartOfPm10(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }

        return render(request, 'chart/trend-chart-of-pm10.html', context=context)

    def post(self, request):
        # 从POST请求中获取省份信息
        province = request.POST.get('province')
        # 查询指定省份的pm10数据，并按时间降序排列
        province_aqi = DatasetInfo.objects.filter(province=province).order_by('-time')
        # 提取数据的日期和pm10值，转化为列表
        dates = [record[0] for record in province_aqi.values_list("time")]
        pm10_values = [record[0] for record in province_aqi.values_list("pm10")]

        # 将日期和pm2.5值列表封装为字典
        province_dict = {
            "dates": dates,
            "pm10_values": pm10_values
        }
        # 返回包含AQI数据的JSON响应
        return JsonResponse(province_dict)


class TrendChartOfSo2(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }

        return render(request, 'chart/trend-chart-of-so2.html', context=context)

    def post(self, request):
        # 从POST请求中获取省份信息
        province = request.POST.get('province')
        # 查询指定省份的So2数据，并按时间降序排列
        province_aqi = DatasetInfo.objects.filter(province=province).order_by('-time')
        # 提取数据的日期和So2值，转化为列表
        dates = [record[0] for record in province_aqi.values_list("time")]
        so2_values = [record[0] for record in province_aqi.values_list("so2")]

        # 将日期和So2值列表封装为字典
        province_dict = {
            "dates": dates,
            "so2_values": so2_values
        }
        # 返回包含AQI数据的JSON响应
        return JsonResponse(province_dict)


class TrendChartOfNo2(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }

        return render(request, 'chart/trend-chart-of-no2.html', context=context)

    def post(self, request):
        # 从POST请求中获取省份信息
        province = request.POST.get('province')
        # 查询指定省份的No2数据，并按时间降序排列
        province_aqi = DatasetInfo.objects.filter(province=province).order_by('-time')
        # 提取数据的日期和No2值，转化为列表
        dates = [record[0] for record in province_aqi.values_list("time")]
        no2_values = [record[0] for record in province_aqi.values_list("no2")]

        # 将日期和No2值列表封装为字典
        province_dict = {
            "dates": dates,
            "no2_values": no2_values
        }
        # 返回包含AQI数据的JSON响应
        return JsonResponse(province_dict)


class TrendChartOfCo(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }

        return render(request, 'chart/trend-chart-of-co.html', context=context)

    def post(self, request):
        # 从POST请求中获取省份信息
        province = request.POST.get('province')
        # 查询指定省份的co数据，并按时间降序排列
        province_aqi = DatasetInfo.objects.filter(province=province).order_by('-time')
        # 提取数据的日期和co值，转化为列表
        dates = [record[0] for record in province_aqi.values_list("time")]
        co_values = [record[0] for record in province_aqi.values_list("co")]

        # 将日期和co值列表封装为字典
        province_dict = {
            "dates": dates,
            "co_values": co_values
        }
        # 返回包含AQI数据的JSON响应
        return JsonResponse(province_dict)


class TrendChartOfO3(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }

        return render(request, 'chart/trend-chart-of-o3.html', context=context)

    def post(self, request):
        # 从POST请求中获取省份信息
        province = request.POST.get('province')
        # 查询指定省份的o3数据，并按时间降序排列
        province_aqi = DatasetInfo.objects.filter(province=province).order_by('-time')
        # 提取数据的日期和o3值，转化为列表
        dates = [record[0] for record in province_aqi.values_list("time")]
        o3_values = [record[0] for record in province_aqi.values_list("o3")]

        # 将日期和o3值列表封装为字典
        province_dict = {
            "dates": dates,
            "o3_values": o3_values
        }
        # 返回包含AQI数据的JSON响应
        return JsonResponse(province_dict)


class AQIMonthlyDistribution(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 准备传入模板的上下文数据
        context = {
            'username': username,
        }

        return render(request, 'chart/AQI-indicator-monthly-distribution.html', context=context)

    def post(self, request):
        aqi_data = {}
        # 爬取实时本月的北上广一线AQI数据
        for base_city in ["北京", "上海", "广州"]:
            if base_city == "广州":
                province_name = '广东'
            else:
                province_name = base_city
            crawler = AirPollutionCrawler(city=base_city, province_name=province_name)
            air_data = crawler.run()
            aqi_data[base_city] = air_data
        return JsonResponse(aqi_data)


class AQIDistribution(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 查询DatasetInfo模型，按province字段分组，仅取province值，转换为列表
        provinces_list = DatasetInfo.objects.values('province').annotate(
            _province=Cast('province', output_field=CharField())
        ).values_list('_province', flat=True).distinct()

        # 准备传入模板的上下文数据
        context = {
            'username': username,
            'provinces': list(set(provinces_list)),
        }

        return render(request, 'chart/AQI-distribution.html', context=context)

    def post(self, request):
        # 从POST请求中获取省份和日期信息
        province = request.POST.get('province')
        date = request.POST.get('date')
        # 把日期字符串转换为日期类型
        date = datetime.strptime(date, '%Y-%m-%d')
        # 查询指定年月的数据
        province_aqi = DatasetInfo.objects.filter(
            time__year=date.year,
            time__month=date.month,
            province=province
        )

        # 提取数据
        aqi_values = [record[0] for record in province_aqi.values_list("aqi")]
        primary_pollutant = [record[0] for record in province_aqi.values_list("primary_pollutant")]
        for index, aqi_item in enumerate(aqi_values):
            # 计算污染等级
            if aqi_item <= 50:
                aqi_values[index] = '优'
            elif aqi_item <= 100:
                aqi_values[index] = '良'
            elif aqi_item <= 150:
                aqi_values[index] = '轻度污染'
            elif aqi_item <= 200:
                aqi_values[index] = '中度污染'
            elif aqi_item <= 300:
                aqi_values[index] = '重度污染'
            else:
                aqi_values[index] = '严重污染'

        # 统计AQI等级的每月占比
        counter = Counter(aqi_values)
        aqi_list = []
        for item, count in counter.items():
            aqi_list.append({"value": count, "name": item})

        # 统计首要污染物的每月占比
        counter = Counter(primary_pollutant)
        pollutant_list = []
        for item, count in counter.items():
            if item != '—':
                pollutant_list.append({"value": count, "name": item})

        json_response = {
            'province': province,
            'aqi_values': aqi_list,
            'dates': date.strftime('%Y-%m'),
            'primary_pollutant': pollutant_list
        }
        return JsonResponse(json_response)


class AQIMapDistribution(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')

        # 准备传入模板的上下文数据
        context = {
            'username': username,
        }

        return render(request, 'chart/AQI-map-distribution.html', context=context)

    def post(self, request):

        spider = AirPollutionRealTimeDataCrawler()
        map_data = spider.run()
        return_data = []
        province_city_map = {
            '北京市': '北京',
            '天津市': '天津',
            '石家庄市': '河北',
            '太原市': '山西',
            '呼和浩特市': '内蒙古',
            '沈阳市': '辽宁',
            '长春市': '吉林',
            '哈尔滨市': '黑龙江',
            '上海市': '上海',
            '南京市': '江苏',
            '杭州市': '浙江',
            '合肥市': '安徽',
            '福州市': '福建',
            '南昌市': '江西',
            '济南市': '山东',
            '郑州市': '河南',
            '武汉市': '湖北',
            '长沙市': '湖南',
            '广州市': '广东',
            '南宁市': '广西',
            '海口市': '海南',
            '重庆市': '重庆',
            '成都市': '四川',
            '贵阳市': '贵州',
            '昆明市': '云南',
            '拉萨市': '西藏',
            '西安市': '陕西',
            '兰州市': '甘肃',
            '西宁市': '青海',
            '银川市': '宁夏',
            '乌鲁木齐市': '新疆',
            '台北市': '台湾',
            '香港市': '香港',
            '澳门市': '澳门',
        }
        city_list = [
            '北京市',
            '天津市',
            '石家庄市',
            '太原市',
            '呼和浩特市',
            '沈阳市',
            '长春市',
            '哈尔滨市',
            '上海市',
            '南京市',
            '杭州市',
            '合肥市',
            '福州市',
            '南昌市',
            '济南市',
            '郑州市',
            '武汉市',
            '长沙市',
            '广州市',
            '南宁市',
            '海口市',
            '重庆市',
            '成都市',
            '贵阳市',
            '昆明市',
            '拉萨市',
            '西安市',
            '兰州市',
            '西宁市',
            '银川市',
            '乌鲁木齐市',
            '台北市',
            '香港市',
            '澳门市',
        ]
        for item in map_data:
            if item['name'] in city_list:
                return_data.append(
                    {"name": province_city_map.get(item["name"]), "value": int(item["value"])}
                )
        print(return_data)
        return JsonResponse({'mapData': return_data})


class AirPollutionCrawler:

    def __init__(self, city="北京", data_type="DAY", province_name="北京"):
        self.url = 'https://www.zq12369.com/api/newzhenqiapi.php'
        self.headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,ko;q=0.5',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://www.zq12369.com',
            'Pragma': 'no-cache',
            'Referer': 'https://www.zq12369.com/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        }
        self.cookies = {
            # 对city参数进行url编码，采用用urllib模块的quote方法
            'city': urllib.parse.quote(city),
        }
        self.data = {
            'param': "QXNXclJtVnc5Mlg5S3Z2Zi9JVU1tbWxRRVRNWnlTMkFBMEVibGhHRjZMZ3NKMCtpQ2YrOXpnRGtnVFFQQlJOMlEwV1JVYVN1UmxZT05CaytEL3dMbkwzdjZJbDBRSDJ0MVlBUk9URUdENlRxSElIZVF6cG9HQkpUZzRYeWJGMXVlWkxNSmhWWUFTUTRsenRDQ0Vpb2FxalBZeVo1YXJ0WEQxQnZmSGMxeUVqeWMveHplNmw0aElaTllueDVYOWtSbmhXMjQydDVJSG4xYzlMaG9zaTQrM21QUDRBYk0yMGVQbUdQNjVlNGFPRXVSeXQ2U25vTFppN0M5TldJQ3BEWElXRFV3QytnbHljLzhPZjJRaStNZ09nYjNER2pOU1M0ME1VQjBvMWIrL0pXWWkwei9wTk01K3Yrekw5RDJEYkRvdHFLTlhUSE8vMjQ3ZkdUSFNTRXRRT2p5c2N1SVRXb3d6UWREWExrMVA3QmNCSWpjRDlCYy8yVENmK3pkTzA1THJqNXp2bEZwWXZpb0tBVkhRL1Y0dG5CMnI1RDZmM3hkNURrMWdHd041WElyZ0VmK2pXcDljaU9HaEF3Q3BQamEyazZoV25Kandubmprd2V6U1JaR1doaUpDb0tyemV0LzdIcjM0Q24wRW5lS1gyZnpIbHh0OS96aDZ5aHpta2ZmQWpnaEJQY1lZalp1enB2K0pSa1pGNmZzK3hxWG1DMmg2MkV2NWZCcnlFUEFoUlZCTkpGZ2hvdUY5andIVVJEQndic2k3cnpTQlZqMGNsUUpZRTA1bXlaSzlSV29TU1BMQmJaOEdNU0ptcWh0QTdFYng0by84Qmh0dVh6dThWNjFXK09PaVJtdE5lT1UyQkJjQUJkRmJmUE9URkcvRnJteEZFSEVuOHdaL2RSUTI4dzVYRFNhbERwaCtrbVlTNE1TbUpYOGRsUXMySFBiS01nOE5TNXdiVEk4RzQyV0haSFNsc2F4R1I5LzdVM1ZySmRxbXdyaHQzanNuQ2NPREZjTW0vUlBGelpvY0ZUMTlDZ0pkVUp0UTFpRGJ2WFFURloxZ3RmRU1OYVluelFUZjAxNXkwODN0UWpuckZWdmozSHBnaXBQeGtTVUFvMW44amdrTkI2ZDJKUkdQRGZhSE1COU9lS1JhZStOcWc9",
        }
        self.obj = {
            "city": city,
            "type": data_type,
            "startTime": "2024-03-01 00:00:00",
            "endTime": "2024-03-31 23:00:00"
        }
        self.province_name = province_name
        self.response_data = ""

    def get_data(self):
        """
        try:
            # 先得到加密的param
            js_ctx = execjs.compile(open("request_encrypt.js", "r", encoding="utf-8").read())
            # 调用js代码中的mygetParam方法，传入obj参数
            param = js_ctx.call("mygetParam", self.obj)
            self.data = {
                'param': param
            }
            response = requests.post(
                url=self.url,
                cookies=self.cookies,
                headers=self.headers,
                data=self.data
            )
            print(response.text)
            self.response_data = response.text
        except Exception as e:
            print(e)
        """
        # 先得到加密的param
        request_encrypt_path = os.path.join(settings.STATICFILES_DIRS[0], "js\\request_encrypt.js")
        js_ctx = execjs.compile(open(request_encrypt_path, "r", encoding="utf-8").read())
        # 调用js代码中的mygetParam方法，传入obj参数
        param = js_ctx.call("mygetParam", self.obj)
        self.data = {
            'param': param
        }
        # print(param)
        response = requests.post(
            url=self.url,
            cookies=self.cookies,
            headers=self.headers,
            data=self.data
        )
        self.response_data = response.text

    def parse_data(self):
        return_list = []
        response_decrypt_path = os.path.join(settings.STATICFILES_DIRS[0], "js\\response_decrypt.js")
        js_ctx = execjs.compile(open(response_decrypt_path, "r", encoding="utf-8").read())
        air_data = js_ctx.call("getData", self.response_data)
        for row in air_data['rows']:
            row['city'] = self.obj['city']
            # 通过row['aqi']来计算污染等级
            if row['aqi'] <= 50:
                row['rank'] = '优'
            elif row['aqi'] <= 100:
                row['rank'] = '良'
            elif row['aqi'] <= 150:
                row['rank'] = '轻度污染'
            elif row['aqi'] <= 200:
                row['rank'] = '中度污染'
            elif row['aqi'] <= 300:
                row['rank'] = '重度污染'
            else:
                row['rank'] = '严重污染'

            return_list.append([
                int(row['time'].split('-')[-1]),
                int(row['aqi']),
                int(row['pm2_5']),
                int(row['pm10']),
                float(row['co']),
                int(row['no2']),
                int(row['so2']),
                row['rank'],
            ])

        return return_list

    def run(self):
        self.get_data()
        return self.parse_data()


class AirPollutionRealTimeDataCrawler:

    def __init__(self):
        self.url = "https://air.cnemc.cn:18007/CityData/GetAllCityRealTimeAQIModels"
        self.headers = {
            "Referer": "https://air.cnemc.cn:18007/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
        }
        self.cookies = {
            'Hm_lvt_0b8b0a2a4a45cbaaa6f549dcad3329a6': '1711543901,1711606757,1712012305,1713945652',
            'Hm_lpvt_0b8b0a2a4a45cbaaa6f549dcad3329a6': '1713945652',
            'Hm_lvt_aadbcc83cc37610f46f503983c444e90': '1711543901,1711606757,1712012305,1713945652',
            'Hm_lpvt_aadbcc83cc37610f46f503983c444e90': '1713945652',
        }

        self.data = {}


    def get_data(self):
        try:
            response = requests.get(
                self.url,
                headers=self.headers,
                cookies=self.cookies,
                verify=False,
            )
            return response.json()
        except Exception as e:
            print(e)
            return {}

    def parse_data(self, js_dict):
        return_list = []
        for item in js_dict:
            return_list.append({
                "name": item['Area'],
                "value": item['AQI']
            })
        return return_list

    def run(self):
        return self.parse_data(self.get_data())


class AQITrendAnalysis(View):
    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')
        # 准备传入模板的上下文数据
        context = {
            'username': username,
        }
        return render(request, 'chart/AQI-trend-analysis.html', context=context)

    def post(self, request):
        # 使用Pandas导入media文件夹中的所有CSV文件，并将其合并为一个DataFrame
        df_all = pd.concat(
            [pd.read_csv(os.path.join(settings.MEDIA_ROOT, 'datasets', f)) for f in
             os.listdir(os.path.join(settings.MEDIA_ROOT, 'datasets')) if f.endswith('.csv')],
            ignore_index=True
        )

        df_all['time'] = pd.to_datetime(df_all['time'])
        df_all.set_index('time', inplace=True)
        monthly_aqi = df_all.groupby(by=pd.Grouper(freq='ME')).mean(numeric_only=True)['aqi']

        # 将monthly_aqi的index转换为dates列表
        dates = [date.date() for date in monthly_aqi.index]
        # 将monthly_aqi的values转换为列表
        values = monthly_aqi.values.tolist()
        values = [round(v, 1) for v in values]

        aqi_dict = {
            'dates': dates,
            'values': values,
        }

        return JsonResponse(aqi_dict)


class PollutantCorrelationAnalysis(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')
        # 准备传入模板的上下文数据
        context = {
            'username': username,
        }
        return render(request, 'chart/pollutant-correlation-analysis.html', context=context)

    def post(self, request):

        # 使用Pandas导入media文件夹中的所有CSV文件，并将其合并为一个DataFrame
        df_all = pd.concat(
            [pd.read_csv(os.path.join(settings.MEDIA_ROOT, 'datasets', f)) for f in
             os.listdir(os.path.join(settings.MEDIA_ROOT, 'datasets')) if f.endswith('.csv')],
            ignore_index=True
        )
        df_all['time'] = pd.to_datetime(df_all['time'])
        df_all.set_index('time', inplace=True)

        # 提取AQI和6种污染物的列
        pollutants = ['aqi', 'pm2_5', 'pm10', 'co', 'no2', 'so2', 'o3']
        subset = df_all[pollutants]

        # 计算相关矩阵
        corr_matrix = subset.corr()
        corr_matrix = corr_matrix.apply(lambda x: x.round(2))
        corr_matrix_list = corr_matrix.values.tolist()

        aqi_dict = {
            'corr_matrix': corr_matrix_list,
        }

        return JsonResponse(aqi_dict)


class AQILevelDistribution(View):
    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')
        # 准备传入模板的上下文数据
        context = {
            'username': username,
        }
        return render(request, 'chart/AQI-level-distribution.html', context=context)

    def post(self, request):
        # 使用Pandas导入media文件夹中的所有CSV文件，并将其合并为一个DataFrame
        df_all = pd.concat(
            [pd.read_csv(os.path.join(settings.MEDIA_ROOT, 'datasets', f)) for f in
             os.listdir(os.path.join(settings.MEDIA_ROOT, 'datasets')) if f.endswith('.csv')],
            ignore_index=True
        )
        df_all['time'] = pd.to_datetime(df_all['time'])
        df_all.set_index('time', inplace=True)
        # 将AQI的值，按照一定范围划分成“0-50优、51-100良、101-150轻度污染、151-200中度污染、201-300重度污染、>300严重污染”
        # 定义一个函数，根据AQI值返回质量等级
        def aqi_to_grade(aqi):
            if aqi <= 50:
                return '优'
            elif aqi <= 100:
                return '良'
            elif aqi <= 150:
                return '轻度污染'
            elif aqi <= 200:
                return '中度污染'
            elif aqi <= 300:
                return '重度污染'
            else:
                return '严重污染'

        # 应用函数到AQI列，并创建新的列 'quality_grade'
        df_all['quality_grade'] = df_all['aqi'].apply(aqi_to_grade)

        # 统计每个QualityGrade的出现次数
        quality_grade = df_all['quality_grade'].value_counts()
        quality_grade_counts = list(quality_grade.values)

        aqi_level_dict = {
            'quality_grade_counts': [int(x) for x in quality_grade_counts]
        }

        return JsonResponse(aqi_level_dict)


class AQIConcentrationDistribution(View):

    def get(self, request):
        # 获取用户名
        username = request.COOKIES.get('user_name')
        # 准备传入模板的上下文数据
        context = {
            'username': username,
        }
        return render(request, 'chart/AQI-concentration-distribution.html', context=context)

    def post(self, request):
        pollution = request.POST.get('pollution')

        # 使用Pandas导入media文件夹中的所有CSV文件，并将其合并为一个DataFrame
        df_all = pd.concat(
            [pd.read_csv(os.path.join(settings.MEDIA_ROOT, 'datasets', f)) for f in
             os.listdir(os.path.join(settings.MEDIA_ROOT, 'datasets')) if f.endswith('.csv')],
            ignore_index=True
        )
        df_all['time'] = pd.to_datetime(df_all['time'])
        df_all.set_index('time', inplace=True)

        # 直方图列表
        pollutants = ['pm2_5', 'pm10', 'co', 'no2', 'so2', 'o3']
        pollutant = []
        if pollution in pollutants:
            pollutant = df_all[pollution].dropna()

        bins = 30
        x_edges, y_counts = np.histogram(pollutant, bins)

        # 将x_edges转换为柱子中心
        x_centers = (x_edges[:-1] + x_edges[1:]) / 2
        js_pollutant = {
            'y_data': x_centers.tolist(),
            'x_data': [round(y, 1) for y in y_counts.tolist()],
        }
        print(js_pollutant)
        return JsonResponse(js_pollutant)
